<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="80px">
      <el-form-item label="收料通知单编号" prop="receiptNoteNo">
        <el-input v-model="queryParams.receiptNoteNo" placeholder="请输入收料通知单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="送货单编号" prop="deliveryNoteNo">
        <el-input v-model="queryParams.deliveryNoteNo" placeholder="请输入送货单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="供货商编码" prop="supplierCode">
        <el-input v-model="queryParams.supplierCode" placeholder="请输入供货商编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:receipt:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:receipt:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:receipt:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:receipt:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="receiptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
      <el-table-column label="收料通知单编号" align="center" prop="receiptNoteNo" min-width="160" />
      <el-table-column label="采购订单编号" align="center" prop="orderNo" min-width="160" />
      <el-table-column label="送货单编号" align="center" prop="deliveryNoteNo" min-width="160" />
      <el-table-column label="供货商编码" align="center" prop="supplierCode" min-width="140" />
      <el-table-column label="供应商名称" align="center" prop="supplierName" min-width="180" />
      <el-table-column label="收料日期" align="center" prop="receiptDate" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receiptDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货人" align="center" prop="receiver" min-width="140" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="240">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="info"
            icon="el-icon-search"
            style="border-radius: 18px; padding: 6px 12px; margin-right: 8px;"
            @click="viewBarcodes(scope.row)"
          >查看箱码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:receipt:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:receipt:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改收料通知单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="扫码">
              <el-input v-model="scanInput" placeholder="支持送货单号/箱码" clearable @keyup.enter.native="handleScan" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收料人">
              <el-input v-model="form.receiver" placeholder="请输入收料人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="供货商名称">
              <el-input v-model="supplierName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="带入同批次">
              <el-switch v-model="carrySameBatch" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">收料清单</el-divider>
        <el-table :data="receiptItemList">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="存货编码" prop="inventoryCode" />
          <el-table-column label="存货名称" prop="inventoryName" />
          <el-table-column label="订单数量" prop="orderQuantity" />
          <el-table-column label="未送料数量" prop="unbarcodedQuantity" />
          <el-table-column label="本次送货数量" prop="batchQuantity" />
          <el-table-column label="明细状态" prop="itemStatus" />
          <el-table-column label="箱数" prop="boxCount" />
        </el-table>

        <el-divider content-position="center">箱码列表</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteBizReceiptBarcode">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="bizReceiptBarcodeList" :row-class-name="rowBizReceiptBarcodeIndex" @selection-change="handleBizReceiptBarcodeSelectionChange" ref="bizReceiptBarcode">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="60"/>
          <el-table-column label="箱码" prop="barcode" width="180" />
          <el-table-column label="存货编码" prop="inventoryCode" width="140" />
          <el-table-column label="批次号" prop="batchNo" width="140" />
          <el-table-column label="数量" prop="packQuantity" width="100" />
          <el-table-column label="计量单位" prop="unitName" width="100" />
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReceipt, getReceipt, delReceipt, addReceipt, updateReceipt } from "@/api/system/receipt"
import { listBarcode } from "@/api/system/barcode"
import { listNote, getNote } from "@/api/system/note"
import { listPurchaseOrderItems } from "@/api/system/purchase_order"
import { listUnit } from "@/api/system/unit"

export default {
  name: "Receipt",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedBizReceiptBarcode: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 收料通知单表格数据
      receiptList: [],
      // 收料通知单箱码明细表格数据
      bizReceiptBarcodeList: [],
      // 收料清单聚合数据
      receiptItemList: [],
      // 采购订单明细缓存
      poItemsById: {},
      poItemsByInv: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 顶部扫码与同批次
      scanInput: "",
      carrySameBatch: true,
      supplierName: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        receiptNoteNo: null,
        deliveryNoteNo: null,
        supplierCode: null,
        // 默认按创建时间倒序
        orderByColumn: 'created_time',
        isAsc: 'desc'
      },
      // 表单参数
      form: {},
      // 表单校验（简化：前端不强制必填，依赖后端校验约束）
      rules: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询收料通知单列表 */
    getList() {
      this.loading = true
      listReceipt(this.queryParams).then(response => {
        this.receiptList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        receiptNoteId: null,
        receiptNoteNo: null,
        deliveryNoteId: null,
        deliveryNoteNo: null,
        supplierCode: null,
        receiptDate: null,
        receiptStatus: null,
        totalBoxes: null,
        totalQuantity: null,
        receiver: null,
        receivedTime: null,
        inspector: null,
        inspectionTime: null,
        qualityResult: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        remark: null,
        delFlag: null
      }
      this.scanInput = ""
      this.carrySameBatch = true
      this.supplierName = ""
      this.bizReceiptBarcodeList = []
      this.receiptItemList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.receiptNoteId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加收料通知单"
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset()
      const receiptNoteId = row.receiptNoteId || this.ids
      const response = await getReceipt(receiptNoteId)
      this.form = response.data
      // supplierName 由列表返回字段赋值（若存在）
      this.supplierName = response.data.supplierName || ""
      // 补充箱码计量单位，兼容后端仅返回 unitCode
      const rawList = Array.isArray(response.data.bizReceiptBarcodeList) ? response.data.bizReceiptBarcodeList : []
      this.bizReceiptBarcodeList = rawList.map(x => ({
        ...x,
        unitName: x.unitName || ''
      }))
      // 通过 unitCode 获取单位名称，确保显示为计量名称
      await this.fillUnitNamesForBarcodes(this.bizReceiptBarcodeList)
      // 加载采购订单明细以补足存货名称与订单数量
      if (this.form.orderNo) {
        await this.loadPOItemsAndCompute(this.form.orderNo)
      } else {
        this.computeReceiptItems()
      }
      this.open = true
      this.title = "收料详情"
    },
    /** 扫码处理：支持送货单号或箱码 */
    async handleScan() {
      const value = (this.scanInput || '').trim()
      if (!value) {
        this.$modal.msgError("请输入送货单号或箱码")
        return
      }
      try {
        // 1) 尝试按送货单号查询（仅支持已发货 CONFIRMED）
        const noteRes = await listNote({ deliveryNoteNo: value })
        if (noteRes && Array.isArray(noteRes.rows) && noteRes.rows.length > 0) {
          const confirmedRows = noteRes.rows.filter(r => r.deliveryStatus === 'CONFIRMED')
          if (confirmedRows.length === 0) {
            this.$modal.msgError("仅支持已发货的送货单号")
            return
          }
          const note = confirmedRows.find(r => r.deliveryNoteNo === value) || confirmedRows[0]
          this.form.deliveryNoteId = note.deliveryNoteId
          this.form.deliveryNoteNo = note.deliveryNoteNo
          this.form.orderNo = note.orderNo
          this.form.supplierCode = note.supplierCode
          this.supplierName = note.supplierName || this.supplierName

          // 获取该送货单详情（箱码与送货清单）
          const detailRes = await getNote(note.deliveryNoteId)
          const barcodeList = (detailRes.data && detailRes.data.bizDeliveryBarcodeList) ? detailRes.data.bizDeliveryBarcodeList : []
          const batchList = (detailRes.data && detailRes.data.bizDeliveryBatchList) ? detailRes.data.bizDeliveryBatchList : []
          const batchNoById = {}
          batchList.forEach(b => {
            if (b.deliveryBatchId != null) {
              batchNoById[b.deliveryBatchId] = b.batchNo
            }
          })

          // 覆盖箱码列表（补充批次号映射）
          this.bizReceiptBarcodeList = barcodeList.map(x => ({
            barcodeId: x.barcodeId,
            barcode: x.barcode,
            itemId: x.itemId || null,
            orderNo: note.orderNo,
            inventoryCode: x.inventoryCode,
            batchNo: batchNoById[x.deliveryBatchId] || '',
            packQuantity: x.packQuantity,
            unitCode: x.unitCode,
            unitName: x.unitName || '',
            barcodeStatus: x.barcodeStatus || null,
            createdTime: x.createTime || null
          }))
          // 通过 unitCode 获取单位名称，确保显示为计量名称
          await this.fillUnitNamesForBarcodes(this.bizReceiptBarcodeList)

          // 加载采购订单明细并计算“收料清单”
          await this.loadPOItemsAndCompute(note.orderNo)
          // 补全缺失的 itemId，确保后端能更新采购明细状态
          await this.resolveItemIdsForBarcodes()
          this.scanInput = ''
          return
        }

        // 2) 尝试按箱码查询（保持原逻辑，并补充订单明细）
        const bcRes = await listBarcode({ barcode: value })
        const barcodes = (bcRes && Array.isArray(bcRes.rows)) ? bcRes.rows : []
        if (barcodes.length === 0) {
          this.$modal.msgError("未找到送货单或箱码")
          return
        }
        const first = barcodes[0]
        this.form.deliveryNoteNo = first.deliveryNoteNo || this.form.deliveryNoteNo
        this.form.orderNo = first.orderNo || this.form.orderNo
        this.form.supplierCode = first.supplierCode || this.form.supplierCode
        this.supplierName = first.supplierName || this.supplierName
        // 若后端返回送货单ID则同步（可选）
        if (first.deliveryNoteId) {
          this.form.deliveryNoteId = first.deliveryNoteId
        }

        // 根据“带入同批次”决定带入范围
        let toAdd = []
        if (this.carrySameBatch && first.batchNo) {
          const batchRes = await listBarcode({ batchNo: first.batchNo })
          let batchRows = (batchRes && Array.isArray(batchRes.rows)) ? batchRes.rows : []
          // 同批次且同送货单号
          const sameDelivery = first.deliveryNoteNo || this.form.deliveryNoteNo
          if (sameDelivery) {
            batchRows = batchRows.filter(b => b.deliveryNoteNo === sameDelivery)
          }
          toAdd = batchRows
        } else {
          // 仅带入当前箱码
          toAdd = [first]
        }
        const rows = toAdd.map(b => ({
          barcodeId: b.barcodeId,
          barcode: b.barcode,
          itemId: b.itemId,
          orderNo: b.orderNo,
          inventoryCode: b.inventoryCode,
          inventoryName: b.inventoryName || '',
          batchNo: b.batchNo,
          packQuantity: b.packQuantity,
          unitCode: b.unitCode,
          unitName: b.unitName || '',
          barcodeStatus: b.barcodeStatus,
          createdTime: b.createdTime || null
        }))
        this.mergeBarcodes(rows)
        // 通过 unitCode 获取单位名称，确保显示为计量名称
        await this.fillUnitNamesForBarcodes(this.bizReceiptBarcodeList)
        // 加载采购订单明细并计算“收料清单”
        if (this.form.orderNo) {
          await this.loadPOItemsAndCompute(this.form.orderNo)
        } else if (first.orderNo) {
          await this.loadPOItemsAndCompute(first.orderNo)
        } else {
          this.computeReceiptItems()
        }
        // 补全缺失的 itemId，确保后端能更新采购明细状态
        await this.resolveItemIdsForBarcodes()
        this.scanInput = ''
      } catch (e) {
        this.$modal.msgError("查询失败")
      }
    },
    /** 合并箱码到列表并去重 */
    mergeBarcodes(rows) {
      const existedKeys = new Set(this.bizReceiptBarcodeList.map(x => x.barcode || x.barcodeId))
      rows.forEach(r => {
        const key = r.barcode || r.barcodeId
        if (!existedKeys.has(key)) {
          this.bizReceiptBarcodeList.push(r)
          existedKeys.add(key)
        }
      })
      this.computeReceiptItems()
    },
    /** 通过 unitCode 填充单位名称 */
    async fillUnitNamesForBarcodes(list) {
      const codes = Array.from(new Set((list || []).filter(x => (!x.unitName || String(x.unitName).trim() === '') && x.unitCode).map(x => x.unitCode)))
      if (codes.length === 0) return
      const map = {}
      await Promise.all(codes.map(async code => {
        try {
          const resp = await listUnit({ pageNum: 1, pageSize: 1, unitCode: code })
          const r = (resp.rows || [])[0]
          if (r && r.unitName) { map[code] = r.unitName }
        } catch (e) {}
      }))
      this.unitMap = Object.assign({}, this.unitMap, map)
      this.bizReceiptBarcodeList = (this.bizReceiptBarcodeList || []).map(x => ({
        ...x,
        unitName: x.unitName || (x.unitCode && this.unitMap[x.unitCode]) || ''
      }))
    },
    // 加载采购订单明细并计算聚合 */
    async loadPOItemsAndCompute(orderNo) {
      try {
        const res = await listPurchaseOrderItems({ orderNo, pageNum: 1, pageSize: 999 })
        const rows = (res && Array.isArray(res.rows)) ? res.rows : []
        this.poItemsById = {}
        this.poItemsByInv = {}
        rows.forEach(it => {
          if (it.itemId != null) this.poItemsById[it.itemId] = it
          if (it.inventoryCode) this.poItemsByInv[it.inventoryCode] = it
        })
        this.computeReceiptItems()
      } catch (e) {
        this.computeReceiptItems()
      }
    },
    /** 计算收料清单聚合与总箱数/总数量（与送货清单相同的获取思路） */
    computeReceiptItems() {
      const aggMap = new Map()
      let totalBoxes = 0
      let totalQty = 0
      this.bizReceiptBarcodeList.forEach(b => {
        totalBoxes += 1
        const qty = Number(b.packQuantity || 0)
        totalQty += qty
        const key = b.itemId || b.inventoryCode || `key-${b.barcode}`
        let agg = aggMap.get(key)
        if (!agg) {
          const po = (b.itemId && this.poItemsById[b.itemId]) || (b.inventoryCode && this.poItemsByInv[b.inventoryCode]) || {}
          agg = {
            inventoryCode: b.inventoryCode || (po.inventoryCode || ''),
            inventoryName: b.inventoryName || po.inventoryName || '',
            orderQuantity: Number(po.orderQuantity || 0),
            unbarcodedQuantity: Number(po.unbarcodedQuantity || 0),
            batchQuantity: 0,
            boxCount: 0,
            itemStatus: po.itemStatus || ''
          }
          aggMap.set(key, agg)
        }
        agg.boxCount += 1
        agg.batchQuantity += qty
      })
      this.receiptItemList = Array.from(aggMap.values())
      this.form.totalBoxes = totalBoxes
      this.form.totalQuantity = totalQty
    },
    /** 提交按钮 */
    async submitForm() {
      // 提交前同步明细与汇总
      // 补全缺失的 itemId，以确保后端按 itemId 汇总更新状态
      await this.resolveItemIdsForBarcodes()
      this.form.bizReceiptBarcodeList = this.bizReceiptBarcodeList
      this.computeReceiptItems()
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.receiptNoteId != null) {
            updateReceipt(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addReceipt(this.form).then(async response => {
              // 新增成功后关闭弹窗，但仍刷新列表与数据
              const data = response && response.data ? response.data : {}
              if (data.receiptNoteNo) this.form.receiptNoteNo = data.receiptNoteNo
              if (data.receiptNoteId) this.form.receiptNoteId = data.receiptNoteId
              this.$modal.msgSuccess("新增成功，已创建检验计划并更新箱码状态")

              if (this.form.receiptNoteNo) {
                await this.loadBarcodesByReceipt(this.form.receiptNoteNo)
              }
              // 刷新采购订单明细状态并标注到收料清单
              await this.refreshPurchaseItemsStatus()
              // 关闭弹窗
              this.open = false
              // 同步刷新列表，展示新单据
              this.getList()
            })
          }
        }
      })
    },
    // 补全缺失的 itemId：优先通过采购明细视图按 inventoryCode 匹配，若仍缺失则回查条码主表
    async resolveItemIdsForBarcodes() {
      try {
        // 先用已加载的采购明细视图做匹配
        this.bizReceiptBarcodeList = (this.bizReceiptBarcodeList || []).map(x => {
          if (!x.itemId && x.inventoryCode && this.poItemsByInv && this.poItemsByInv[x.inventoryCode]) {
            const po = this.poItemsByInv[x.inventoryCode]
            return { ...x, itemId: po.itemId || x.itemId }
          }
          return x
        })
        // 回查条码主表以补足仍缺失的 itemId
        const needLookup = (this.bizReceiptBarcodeList || []).filter(x => !x.itemId && x.barcode)
        if (needLookup.length > 0) {
          await Promise.all(needLookup.map(async x => {
            try {
              const r = await listBarcode({ barcode: x.barcode, pageNum: 1, pageSize: 1 })
              const b = (r && Array.isArray(r.rows)) ? r.rows[0] : null
              if (b && b.itemId) { x.itemId = b.itemId }
              if (b && b.orderNo && !x.orderNo) { x.orderNo = b.orderNo }
            } catch (e) {}
          }))
        }
      } catch (e) {}
    },
    // 根据收料通知单号拉取并刷新弹窗内箱码列表
    async loadBarcodesByReceipt(receiptNoteNo) {
      try {
        const res = await listBarcode({ receiptNoteNo, pageNum: 1, pageSize: 999, orderByColumn: 'created_time', isAsc: 'desc' })
        const rows = Array.isArray(res.rows) ? res.rows : []
        this.bizReceiptBarcodeList = rows.map(r => ({
          barcodeId: r.barcodeId,
          barcode: r.barcode,
          itemId: r.itemId,
          orderNo: r.orderNo,
          inventoryCode: r.inventoryCode,
          inventoryName: r.inventoryName || '',
          batchNo: r.batchNo,
          packQuantity: r.packQuantity,
          unitCode: r.unitCode,
          unitName: r.unitName || '',
          barcodeStatus: r.barcodeStatus,
          createdTime: r.createdTime || null
        }))
        // 计量单位名兜底
        await this.fillUnitNamesForBarcodes(this.bizReceiptBarcodeList)
        // 重新计算汇总
        this.computeReceiptItems()
      } catch (e) {
        this.$modal.msgError("刷新箱码失败")
      }
    },
    // 刷新采购订单明细状态并写入收料清单
    async refreshPurchaseItemsStatus() {
      const orderNo = this.form.orderNo
      if (!orderNo) return
      try {
        const res = await listPurchaseOrderItems({ orderNo, pageNum: 1, pageSize: 999 })
        const items = Array.isArray(res.rows) ? res.rows : []
        const statusByInv = {}
        items.forEach(i => {
          if (i.inventoryCode) statusByInv[i.inventoryCode] = i.itemStatus || ''
        })
        this.receiptItemList = (this.receiptItemList || []).map(it => ({
          ...it,
          itemStatus: statusByInv[it.inventoryCode] || it.itemStatus || ''
        }))
        const changed = items.filter(i => (i.itemStatus || '').length > 0).length
        if (changed > 0) {
          this.$modal.msgSuccess(`采购明细状态已更新：${changed} 项`) 
        }
      } catch (e) {}
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const receiptNoteIds = row.receiptNoteId || this.ids
      this.$modal.confirm('是否确认删除收料通知单编号为"' + receiptNoteIds + '"的数据项？').then(function() {
        return delReceipt(receiptNoteIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 收料通知单箱码明细序号 */
    rowBizReceiptBarcodeIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 收料通知单箱码明细删除按钮操作 */
    handleDeleteBizReceiptBarcode() {
      if (this.checkedBizReceiptBarcode.length == 0) {
        this.$modal.msgError("请先选择要删除的收料通知单箱码明细数据")
      } else {
        const bizReceiptBarcodeList = this.bizReceiptBarcodeList
        const checkedBizReceiptBarcode = this.checkedBizReceiptBarcode
        this.bizReceiptBarcodeList = bizReceiptBarcodeList.filter(function(item) {
          return checkedBizReceiptBarcode.indexOf(item.index) == -1
        })
        this.computeReceiptItems()
      }
    },
    /** 复选框选中数据 */
    handleBizReceiptBarcodeSelectionChange(selection) {
      this.checkedBizReceiptBarcode = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    viewBarcodes(row) {
      const receiptNoteNo = row && row.receiptNoteNo
      if (!receiptNoteNo) {
        this.$modal.msgError("该行缺少收料通知单编码，无法查看箱码")
        return
      }
      this.$router.push({ path: '/system/barcode', query: { receiptNoteNo } })
    },
    handleExport() {
      this.download('system/receipt/export', {
        ...this.queryParams
      }, `receipt_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
